#include "poller_protocol.h"

bool Send ( int header, const char *payload, int socket )
{
	int error;
	char message[MESSAGE_SIZE];
	memset ( message, '\0', MESSAGE_SIZE );

	sprintf ( message, "%d %s", header, payload );
	if ( ( error = write ( socket, message, strlen(message) + 1 ) ) == -1 )
	{
		if (errno == EPIPE)
		{
			perror ("Send");
			return false;
		}
	}
	
	return true;
}

bool Wait ( int header, char *payload, int socket )
{
	int incomeHeader, error;
	char message[MESSAGE_SIZE];
	memset ( message, '\0', MESSAGE_SIZE );
	memset ( payload, '\0', MESSAGE_SIZE );

	error = read ( socket, message, MESSAGE_SIZE );
	
	if ( error == 0 )
	{
		perror ("Wait");
		return false;
	}	
	
	sscanf ( message, "%d", &incomeHeader );
	strcpy ( payload, &message[2] );
	
	return header == incomeHeader;
}

bool WaitResponse ( int *header, char *payload, int socket )
{
	int error;
	char message[MESSAGE_SIZE];
	memset ( message, '\0', MESSAGE_SIZE );
	memset ( payload, '\0', MESSAGE_SIZE );

	error = read ( socket, message, MESSAGE_SIZE );

	if ( error == 0 )
	{
		perror ("WaitResponse");
		return false;	
	}	

	sscanf ( message, "%d", header);
	strcpy ( payload, &message[2] );
	return true;
}




